package com.grj.parkingsystem.common;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;


@Component
public class JwtUtil {

    @Value("${jwt.secret}")
    private String secret;

    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     * 生成JWT Token
     */
    public String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
                .setClaims(claims)
                .setSubject((String) claims.get("username"))
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis() + 86400000L))
                .signWith(SignatureAlgorithm.HS512, "q1EeZGVcy3AW/msZ2TM6aYmokOcIlE4G5H7kuWk2jOvflVYKYlJEti6KFnPnp5Z8jz8tr4p3sbMY2xnKwCo6Lg==")
                .compact();
    }

    /**
     * 解析JWT Token获取Claims
     */
    public Claims getClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey("q1EeZGVcy3AW/msZ2TM6aYmokOcIlE4G5H7kuWk2jOvflVYKYlJEti6KFnPnp5Z8jz8tr4p3sbMY2xnKwCo6Lg==")
                .parseClaimsJws(token)
                .getBody();
    }

    /**
     * 从Token中获取用户名
     */
    public String getUsernameFromToken(String token) {
        token = token.replaceAll("Bearer ","").trim().replace(" ", ""); // 替换空格为 +
        return getClaimsFromToken(token).getSubject();
    }

    /**
     * 验证Token是否有效
     */
    public boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey("q1EeZGVcy3AW/msZ2TM6aYmokOcIlE4G5H7kuWk2jOvflVYKYlJEti6KFnPnp5Z8jz8tr4p3sbMY2xnKwCo6Lg==").parseClaimsJws(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static void main(String[] args) {
//        // 生成一个适合 HS512 的密钥（512位及以上）
//        SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS512);
//        String secretString = Base64.getEncoder().encodeToString(key.getEncoded());
//        System.out.println(secretString);
        JwtUtil jwtUtil = new JwtUtil();
        String token = jwtUtil.generateToken(Map.of("username", "admin"));
        System.out.println(token);
        System.out.println(jwtUtil.getUsernameFromToken(token));

    }



}    